package tom.reactor.websocket.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Calendar;

/**
 * 收到消息和发送消息分开处理
 * @author ZHUFEIFEI
 */
@Slf4j
@Component
public class DateTimeHandler implements WebSocketHandler {
    @Override
    public Mono<Void> handle(WebSocketSession session) {
        Mono<Void> input = session.receive().log()
                .doOnNext(msg -> {log.info("session : {} receive msg: {}", session.getId(), msg.getPayloadAsText());})
                .map(msg ->  msg.getPayloadAsText())
                .then();
        Flux<String> respData = Flux.interval(Duration.ofSeconds(1L))
                .map(m -> "seq." + m.longValue() + " server time => " + SimpleDateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));
        Mono<Void> output = session.send(respData.map(d -> session.textMessage(d)));
        return Mono.zip(input, output).then();
    }
}
